var express = require('express');
var router = express.Router();
var db = require('../public/javascripts/db');
var config = require('../public/config');

router.get('/', (req, res, next) => {
    // res.send('get history list');
    // console.log('config', config);
    var getSql = 'SELECT * FROM history';
    db.query(getSql, (err, result) => {
        if (err) {
            db.query(
                "CREATE TABLE history(" +
                "id int not null auto_increment," +       //数据库自增id
                "userId varchar(255)," +
                "userName varchar(255), " +
                "algorithm varchar(255), " +
                "percent int," +
                "result varchar(255), " +
                "status int, " +
                "time varchar(255),type varchar(255),leftSrc mediumblob,rightSrc mediumblob,primary key (id))", (err, result) => {
                    if (err) {
                        throw err;
                    } else {
                        console.log('创建表成功')
                    }
                })
            console.log('[SELECT ERROR]-', err.message);
            return;
        }
        // res.send(result[0].leftSrc.toString());
        // console.log('HISTORY INSERT ID:', result);
        // console.log('HISTORY INSERT ID:', result.length);

        var len = result.length;
        for (var i = 0; i < len; i++) {
            result[i].leftSrc = result[i].leftSrc.toString();
            result[i].rightSrc = result[i].rightSrc.toString();
        }
        // console.log('HISTORY INSERT ID:', result[0].userName);
        // var base64 = result[0].leftSrc.slice(0, 50);
        // console.log('HISTORY INSERT ID:', result[0].leftSrc);
        // console.log('HISTORY INSERT ID:', base64);

        res.send(result);

        //执行python脚本
        // var exec = require('child_process').exec;
        // var arg1 = '1.png';
        // var filename = config.pythonPath;
        // exec('python' + ' ' + filename + ' ' + arg1, (err, stdout, stderr) => {
        //     if (err) {
        //         console.log('stderr:', stderr);
        //     } else {
        //         console.log('stdout:', stdout);
        //     }
        // })

    })
})

router.delete('/', (req, res, next) => {
    res.send('delete history');

    // var delSql = 'DELETE FROM history2 WHERE id = 2';
    // var delSql = 'TRUNCATE TABLE history';
    var delSql = 'DELETE FROM history';
    db.query(delSql, (err, result) => {
        if (err) {
            console.log('[DELETE ERROR]-', err.message);
            return;
        }
        console.log('DELETE affectedRows', result);
    })
})

module.exports = router;